/**
 * Created by lixiaodi on 2018/11/9.
 */


mini.parse();
//得到表单/数据表
var refGrid = mini.get("refDatagrid");
var form = new mini.Form("form1");
var form2 = new mini.Form("form2");
var okBtn = mini.get('okBtn');
var btnBoxEl = $('#btnBox');            // 单据操作按钮栏
//var btnBoxEl = mini.get('btnBox');            // 单据操作按钮栏
//绘制表单
var edit_data;
var edit_table = [];//编辑的表格数据
var formSh;
var arr_table = [];//生成表格组件数组
var arr_tab = [];
var arr_tab_table = [];//生成tab表格组件数组
var datepick_main = [];
var arr_cMath_child = [];//所有子表公式
var arr_cMath_main = [];//所有主表公式
var arr_main = {   //存放格式化的保存数据
	    "cTableName": "",
	    "obj" : {}
	};
var taskId;
var assignee = new Array();
var candidateUserIds = new Array();
var candidateGroupIds = new Array();
//弹出窗口路径前缀
var url = bootPATH + "../frame/frame1/pages/";
var taskHandleData;
var formItem = parent.getFormItem();// 菜单跳转后获取数据
console.log(formItem);
 var formSh = localStorage.getItem("formShow");
//
 formSh=$.parseJSON(formSh);
 console.log(formSh);
// var menuId=formSh.menuId;
var isEditState = '';       // 单据是否可编辑状态s
var ids="";

//初始化显示数据表内容
$(function(){

	//批准按钮可用
	okBtn.enable();
	//得到待办任务传来的值
	taskHandleData = localStorage.getItem("taskHandle");

	if(taskHandleData){
		taskHandleData = JSON.parse(taskHandleData);
		formSh = taskHandleData;
		console.log(formSh,'传输到子页面的数据');
		edit_data = formSh.edit_data;
		formsShow();
		if(formSh.processInstanceId){
			var taskId = formSh.processInstanceId;
			console.log(taskId);
            // 判断是否可编辑
            isEditForm(taskId);
			$.ajax({
		         url: ajaxUrl + "/activitiTaskController/listHistoryCommentWithProcessInstanceId.do",
		         type:"post",
		         data:{
		         	taskId : taskId
		         },
		         success: function (data) {
		         	console.log(data.data);
		            var gridTab1Arr = data.data;
		         	//时间格式
		         	for(var i = 0; i < gridTab1Arr.length; i++){
		         		//日期格式转换
		     			if(gridTab1Arr[i].time){
		     				gridTab1Arr[i].time = formatDateSec(gridTab1Arr[i].time);
		     			}
		         	}
		         	console.log(gridTab1Arr);
		         	refGrid.setData(gridTab1Arr);

		         },
		         error: function () {
		             mini.alert("失败");
		         }
		     });
			//流程图显示
            if(taskId){
                fileUrl = ajaxUrl + "/activitiTaskController/getView.do?processInstanceId=" + taskId;
                images = document.getElementById("imgs");
                images.src = fileUrl;
                console.log(images.width);
                console.log(images.height);
            }else{
                mini.alert('暂无流程图');
            }
		}
	}else{
		console.log('没有数据');
	}
	//refGrid.setData(data);
});
//批准（保存数据）
// 判断单据是否可以编辑
function isEditForm(taskId){
    $.ajax({
        url: ajaxUrl + "/activitiTaskController/findControlByProcessInstanceId.do",
        type: 'POST',
        data : {
            processInstanceId : taskId
        },
        success: function (data) {
            isEditState = data.state;
            // 判断是否可编辑（显示单据按钮栏）
            if(isEditState == '1'){
                btnBoxEl.show();
                // 保存按钮可用
                mini.get('saveEl').disable();
            }else{
                btnBoxEl.hide();
            }
        }
    })
}
function SaveData() {

    var formiddd=localStorage.getItem("formidd");
	var mangeId = formSh.id;
    var ids = form2.getData();
    $.ajax({
        url: ajaxUrl + "/activitiTaskController/getNextTaskGroup.do",
        type: 'POST',
        data : {
            id:formiddd,
        	taskId : mangeId
        },
        success: function (data) {
        	console.log(data,'点击批准返回的数据，需要带到子页面');
        	assignee = data.assignee;
        	candidateUserIds = data.candidateUserId;
        	candidateGroupIds = data.candidateGroupId;
            mini.open({
                url: url + "taskWin/approvalWin.html",
                title: "批准", width: 600, height: 400,
                onload: function () {
                    var iframe = this.getIFrameEl();
                    var data = { action: "approval",
                        mangeId: mangeId,
                        ids:ids,
                        assignee:assignee,
                        candidateUserIds:candidateUserIds,
                        candidateGroupIds:candidateGroupIds
                    };
                    console.log(data,'传给子页面的');
                    iframe.contentWindow.SetData(data);
                },
                ondestroy: function (action) {
                    httpRequest();
                }
            });
        },
        error: function (data) {
            console.log("请求失败")
        }
    });

//    if(mangeId){
//    	 $.ajax({
//    	        url: ajaxUrl + "/activitiTaskController/audit_bz.do?taskId="+mangeId+"&comment="+ids.remarks,
//    	        type: 'POST',
//    	        contentType : "application/json",
//    	        success: function (data) {
//    	        	console.log(data);
//    	        	if(data.type == 'success'){
//    	        		mini.alert('操作成功');
//    	            	//提交成功以后，提交按钮禁用
//    	            	okBtn.disable();
//    	        	}else{
//    	        		mini.alert('操作失败');
//    	            	//提交成功以后，提交按钮禁用
//    	            	//okBtn.enable();
//    	        	}
//
//    	            //CloseWindow("save");
//    	        },
//    	        error: function (data) {
//    	        	mini.alert('失败');
//    	            //CloseWindow();
//    	        }
//    	    });
//    }else{
//    	mini.alert('无需要批准的单据');
//    }
}

//父页面给子页面传值
function SetData(data){
	console.log(data.nowTask);
	taskId = data.taskId;
//	$.ajax({
//        url: ajaxUrl,
//        type: 'POST',
//        contentType : "application/json",
//        success: function (data) {
//            CloseWindow("save");
//        },
//        error: function (data) {
//            CloseWindow();
//        }
//    });
}
//提交审批
function onSubmitApproval(){

}
//历史批注(审批列表)
function onShowList(){
	//得到单据id
	//打开批注列表
	mini.open({
        url: url + "activiti/datagridDetail/postilLists.html",
        title: "批注列表",
        width: 600,
        height: 400,
        onload: function () {
            var iframe = this.getIFrameEl();
            var data = {
                action: "see",
                //taskId : row.id
            };
            //iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {
            grid.reload();
        }
    });
}

//请求历史批注
function historyHttp(){
	$.ajax({
        url: ajaxUrl + "/activitiTaskController/audit_bz.do",
        type: 'POST',
        data: jsonString,
        contentType : "application/json",
        success: function (data) {
            CloseWindow("save");
        },
        error: function (data) {
            CloseWindow();
        }
    });
}
//表单绘制
function formsShow(){
	//画组件
    taskHandleData = localStorage.getItem("taskHandle");
    // 请求字段
    var url =  ajaxUrl + "/formltems/findByFormListId.do";
    $.ajax({
        type : 'post',
        url : url,
        data : {
            formId :$.parseJSON(taskHandleData).formListId
            //formId : 126
        },
        dataType : 'json',
        success : function (data) {
        	component_data = data['data'];
            console.log(component_data,'组件');
            for(var i=0;i<component_data.length;i++) {
                if(component_data[i].type == 'tab') {
                    arr_tab.push(component_data[i]);
                }
                if(component_data[i].type.indexOf('datepicker')>-1) {
                    datepick_main.push(component_data[i]);
                }
                if(component_data[i].cMath == "") {
                    component_data[i].cMath = JSON.stringify(component_data[i].cMath);
                }
                //对比表单页面修改
                // if (component_data[i].cTableField.indexOf('single_person') > -1 && component_data[i].type != "table") {// 制单人
                //     single_person_data.push(component_data[i]);
                // }
                if(component_data[i].type.indexOf('buttonedit')>-1) {

                	if(component_data[i].ref != "{}") {
                		var item = $.parseJSON(component_data[i].ref).ref.cTableField;//group_name
//                		if(nodes != null){
//                			for(var k=0;k<nodes.length;k++) {
//                                for (var nod in nodes[k]) {
//                                    if (item == nod) {//保存参照的字段
//                                        refFields[component_data[i].cTableField] = nodes[k][item];
//                                    }
//                                }
//                            }
//                		}
                        
                	}
                }
            }
            create_tab(arr_tab);
            showForm(component_data);//渲染

            //赋值
            console.log(edit_data);

            var formField = $("#formField").children();
            console.log(formField,'formField');
            for(var i = 0; i <formField.length; i++){
                console.log(formField[i].id, 'id');
                if(formField[i].className == 'form_items') {//主表组件

                    var form = new mini.Form("#"+formField[i].id);
                    //var mainFormData = edit_data[formSh.cTableName][0];
                    // 得到主表数据
                    //var mainFormData = edit_data[formSh.cTableName];
                    var mainFormData = edit_data[formSh.cTableName];
                    console.log(mainFormData);
                    var newMainFormData  = {};
                    //处理主表数据
                    for(var key in mainFormData){
                        if(mainFormData[key].indexOf('null') == -1){
                            newMainFormData[key] = jiequ(mainFormData[key],1);

                        }else{
                            newMainFormData[key] = '';
                        }
                    }
                    //赋值
                    //form.setData(edit_data[formSh.cTableName][0], false);
                    console.log(formSh.cTableName);
                    newMainFormData[formSh.cTableName+"_billDate"]=formatDate(newMainFormData[formSh.cTableName+"_billDate"]);
                    console.log(newMainFormData);
                    form.setData(newMainFormData);
                    //form.setData(edit_data, false);
                    var index = formField[i].id.indexOf('buttonedit')

                    if(index > -1) {
                  	  console.log(edit_data);
                  	  for(var item in edit_data[formSh.cTableName]) {
                  		  var setBE = edit_data[formSh.cTableName];
                  		  if(item == formField[i].children[1].children[1].name) {

                              setBE[item]=jiequ(setBE[item],1);
                              console.log(setBE[item]);
                          	  mini.get("right"+formField[i].id).setText(setBE[item]);
                  		  }
                  	  }
                    }
                    edit_form = edit_data[formSh.cTableName];

                }else {//表格
                    if(formField[i].className.indexOf('mini-menu') == -1) {
                        var indexofBloean = formField[i].className.indexOf('mini-tabs');
                        if(indexofBloean == 0){
                            console.log('tab组件赋值');
                            //获取子表组件(根据页签id获取当前页签)
                            var nowTab = mini.get(formField[i].id);
                            //获取页签组
                            var childsTab = nowTab.getTabs();
                            //页签内容区域存放
                            var childTabContents = [];
                            for(var j = 0; j < childsTab.length; j++){
                                childTabContents.push(nowTab.getTabBodyEl(childsTab[j]));
                            }
                            var tabChildGridIds = [];
                            var tabChildGridKeys = [];
                            childTabContents.forEach(function (item,index){
                                tabChildGridIds.push(item.childNodes[2].id);
                                tabChildGridKeys.push(item.childNodes[2].id.split('_')[1]);
                            });
                            //得到数据表格
                            tabChildGridIds.forEach(function (Iditem,index){
                                tabChildGridKeys.forEach(function (keyItem,index){
                                    if(Iditem.indexOf(keyItem) != -1){
                                        //得到表格，赋值
                                        var tabGrid = mini.get(Iditem.match(/dg(\S*)/)[1]);
                                        console.log(edit_data[keyItem]);
                                        tabGrid.setData(edit_data[keyItem]);
                                    }
                                });
                            })
                        }else{
                            var grid = mini.get(formField[i].id.match(/dg(\S*)/)[1]);
                            grid.setData("");
                            var temp = formField[i].childNodes[2].className.split(' ');
                            var mtableName;
                            for(var m=0;m<temp.length;m++) {
                                if(temp[m].indexOf('mtable-')>-1) {
                                    mtableName = temp[m].substring(temp[m].indexOf("-")+1);
                                }
                            }

                            // var e = edit_data[formField[i].id.substring(8)];
                            // for(var k = 0; k <e.length; k++) {
                            //     e[k].cTableName = formField[i].id.substring(8);//加入子表名
                            // }
                            if(edit_data[mtableName] == []){
                                grid.setData([{},{}]);
                            }else {
                                grid.setData(edit_data[mtableName], false);
                            }
                            edit_table.push({
                                cTableName: mtableName,
                                obj: edit_data[mtableName]
                            });
                        }
              	  }
                }
            }
            // 单据禁用(点击编辑以后才可用)
            var formEnable = new mini.Form("formField");
            formEnable.setEnabled(false);
            //$("#formField").attr({readonly:"true"});
            //unmask();
        },
        error : function (message) {
            console.log('失败');
        }
    })
}
//创建表格
function create_table(arr_table,area) {

    arr_table = jsonByGroup(arr_table);//表格按数据库表名分组
    console.log(arr_table,'arr_table分组后');
    for(var i = 0; i < arr_table.length; i++) {
        //arr_table[i]是一个表格

        var id = arr_table[i].c_id;
        var type = arr_table[i].type;
        var mTableName = arr_table[i].cTableName;
        var cols = JSON.parse(arr_table[i].gridColumns);
        var data = arr_table[i].data;
        // var grid = new mini.DataGrid();//js创建表格

        // var tree_data = [];
        for(var r=0;r<cols.length;r++) {

        	console.log(cols[r].columns);
            if(cols[r].columns == undefined) {//无分组
                // tree_data.push(cols[r]);
                cols[r] = setEditor(cols[r]);
            }else {
                var cols2 = cols[r].columns;
                for(var s=0;s<cols2.length;s++) {
                    if(cols2[s].columns == undefined) {//一层分组
                        // tree_data.push(cols2[s]);
                        cols2[s] = setEditor(cols2[s]);
                    }else {
                        var cols3 = cols2[s].columns;
                        for(var t=0;t<cols3.length;t++) {
                            // tree_data.push(cols3[t]);
                            cols3[t] = setEditor(cols3[t]);
                        }
                    }
                }
            }
        }
        console.log(cols,'整理分组');
        //个性化
        function setEditor(col) {

            if(col.editor.type == 'combobox') {//这一列是下拉框

                //设置下拉内容
                var combo_data = [];
                for(var k=0;k<data.length;k++) {
                    if(col.name == data[k].col_id) {
                        var combo_arr = data[k].cCombo.split(/[(\r\n)\r\n]+/);
                        combo_data = [];
                        for(var p=0;p<combo_arr.length;p++) {
                            combo_data.push({
                                'id':combo_arr[p],'text':combo_arr[p]
                            })
                        }
                    }
                }
                col.editor = {data:combo_data,type:col.editor.type};

            }else if(col.editor.type == 'datepicker') {

                if(type == 'tab_table') {
                    col.editor = {type:col.editor.type};
                }
                //格式化
                for(var k=0;k<data.length;k++) {
                    if(col.name == data[k].col_id) {
                        col.dateFormat = data[k].cFormat;
                        //默认设置当前日期
                        if(data[k].cDateDefault == 'true') {
                            datepick_child.push(data[k]);
                        }
                    }
                }
            }else if(col.editor.type == 'buttonedit') {

                if(type == 'tab_table') {
                    col.editor = {type:col.editor.type};
                }
                for(var k=0;k<data.length;k++) {
                    if(col.name == data[k].col_id) {
                        //弹窗
                        col.editor.onbuttonclick = "onSelectRef("+id+","+data[k].ref+")";
                    }
                }
            }else if(col.editor.type  == 'tab_table') {

                col.editor = {type:col.editor.type};

            }else {//文本类组件
                col.editor = {type:col.editor.type};
                //设置长度限制
                for(var k=0;k<data.length;k++) {
                    if(col.name == data[k].col_id && data[k].cLength != 0) {
                        col.editor.maxLength = data[k].cLength;
                    }
                }
            }
            //表格单元格验证
            for(var x=0;x<data.length;x++) {
                if(col.name == data[x].col_id) {
                    if(data[x].cNull == 'true') {//必填
                        if(data[x].cRequire == 'none') {//不验证
                            col.vtype="required";
                        }else {//验证
                            col.vtype="required;"+data[x].cRequire;
                        }
                    }else {//非必填
                        if(data[x].cRequire == 'none') {//不验证

                        }else {//验证
                            col.vtype=""+data[x].cRequire;
                        }
                    }
                }
            }
            return col;
        }
        var $clone = "    <div  id='dg"+id+"'>\n" +
            "        <div class='mini-toolbar' style='border-bottom:0;padding:0px;'>\n" +
            "            <table style='width:100%;'>\n" +
            "                <tr>\n" +
            "                    <td style='width:100%;'>\n" +
            "                        <a class='mini-button' iconCls='icon-add' onclick='onAddRow(e," + id + ")' plain='true'>新增行</a>\n" +
            "                        <a class='mini-button' iconCls='icon-remove' onclick='onRemoveRow(e," + id + ")' plain='true'>删除行</a>\n" +
            "                     </td>\n" +
            "                    \n" +
            "                </tr>\n" +
            "            </table>           \n" +
            "        </div>"

        $clone += "<div id='"+id+"' class='mini-datagrid mtable-"+mTableName+"' style=''\n>" +
            " contextMenu='#gridMenu" +id+ "'>\n" +
            "    <div property='columns'></div>\n" +
            "</div></div>";

        var gridMenu = "<ul id='gridMenu"+id+"' class='mini-contextmenu'  onbeforeopen='onBeforeOpenGrid(e," + id + ")'>\n" +
            "   <li name='add' iconCls='icon-add' onclick='onAddRow(e," + id + ")'>增行</li>\n" +
            "   <li name='remove' iconCls='icon-remove' onclick='onRemoveRow(e," + id + ")'>删行</li>\n" +
            "</ul>";


        if(area == 'tab') {
            var tabs = mini.get(data[i].tabs_id);
            var tabEl = tabs.getTabBodyEl(tabs.getTab(data[i].tab_id));
            var param = {
                area: "div[id='" + tabEl.id + "']",
                c_id: id,//整个页签
                tab_id: data[i].tab_id//插入的当前页签
            }
            // grid.render(document.getElementById(tabEl.id));
            console.log(tabEl.id);
            var field = escapeJquery(tabEl.id);
            $("#"+field).append($clone);
            $("#"+field).append(gridMenu);

        }else {
            // grid.render(document.getElementById("formField"));

            $("#formField").append($clone);
            $("#formField").append(gridMenu);
        }
        mini.parse();
        var grid = mini.get(id);
        grid.set({
            url: "",
            columns: cols,
            //multiSelect:true,
            allowResize:true,
            allowCellEdit:true,
            allowCellSelect:true,
            cellEditAction: "celldblclick",
            allowRowSelect: true,
            showPager:false,
            editNextOnEnterKey:true,
            editNextRowCell:true,
            showModified: false,
            allowCellValid: true,

            //allowRowSelect:false,
            //enableHotTrack:false,
        });
        $("#dg"+id).css({
            width: arr_table[i].iWidth,
            height: arr_table[i].iLabHeight,
            "min-height": 100,
            top: arr_table[i].iConY,
            left: arr_table[i].iConX,
            position: "absolute"
        });
        $("#"+id).css({
            width: arr_table[i].iWidth,
            height: arr_table[i].iLabHeight,
            "min-height": 70
        });
        grid.setData([{},{}]);
        new CopyExcel(grid);        //Excel互操作插件
        mini.parse();
        addRow(id);//回车增加一行

        mini.get(id).on('cellbeginedit',function (e) {
            // console.log(e.sender);
            currentCell = e;
            // e.row['round'] = '123';

        });

        var cMath; //公式
        // mini.get(id).on('drawCell',function (e) {
        //     // e.sender.id//表格id
        //     var data;
        //     for(var o=0;o<arr_table.length;o++) {
        //         if(arr_table[o].c_id == e.sender.id) {
        //             data = arr_table[o].data;
        //         }
        //     }
        //     for(var p=0;p<data.length;p++) {
        //         if(data[p].cTableField == e.field){
        //             cMath = $.parseJSON(data[p].cMath).newStrEn;
        //         }
        //     }
        //
        //     console.log(cMath,'公式');
        //     var str = cMath;
        //     // if(cMath != '' && cMath != undefined) {
        //     //
        //     // 	var param = setLinkage(e,cMath,str,'table');
        //     //     str = param.str;
        //     //     var mathType = param.mathType;
        //     //     var linkType = param.linkType;
        //     //     var linkId = param.linkId;//关联类型设置的id
        //     //     var grid = mini.get(e.sender.id);
        //     //     if(mathType == 'mathType_other') {//计算/拼接
        //     //         var thisStr = str.split('=')[0];
        //     //         if(currentCell != undefined) {
        //     //             if(thisStr.indexOf(currentCell.field) == -1 || linkType.indexOf('base') >-1) {
        //     //                 var result = evil(str);
        //     //                 console.log(result);
        //     //                 console.log(!isNaN(result));
        //     //
        //     //                 if( result!=undefined && result!='$') {
        //     //                     e.cellHtml = result;
        //     //                     e.row[e.field] = result;
        //     //                 }
        //     //             }
        //     //         }
        //     //     }else if(mathType == 'mathType_link') {//关联
        //     //     	if(str.fileldValue != undefined){
        //     //     		$.ajax({
        //     //                 type : 'POST',
        //     //                 url : ajaxUrl+'/dbsource/casacade.do ',
        //     //                 dataType : 'json',
        //     //                 //contentType: "application/json",
        //     //                 data : str,
        //     //                 success: function (data) {
        //     //                 	//e.cellHtml = data.data;
        //     //                 	//e.row[e.field] = data.data;
        //     //                 	var up = {};
        //     //                 	up[e.field] = 'cs';
        //     //                 	mini.get(e.sender.id).updateRow(e.row, up);
        //     //                 },
        //     //                 error: function (jqXHR, textStatus, errorThrown) {
        //     //                 	mini.alert('失败');
        //     //                 }
        //     //             })
        //     //     	}
        //     //     }
        //     // }
        // })

    }//每个arr[i]是一个表格
}
//创建页签
function create_tab(arr_tab) {

    arr_tab = jsonByGroup(arr_tab);//表格按数据库表名分组
    console.log(arr_tab,'arr_tab分组后');
    for(var i = 0; i < arr_tab.length; i++) {
        //arr_table[i]是一个表格
        var id = arr_tab[i].c_id;
        var data = arr_tab[i].data;
        var div = '';
        for(var j=data.length-1;j>=0;j--) {
            div = "<div name='"+data[j].tab_id+"' title='"+data[j].cTabText+"'> </div>\n"+div;
        }

        var $clone = "<div id='"+id+"'class='mini-tabs' activeIndex='0'>\n"+div+"</div>";
        $('#formField').append($clone);
        mini.parse();
        $("#"+id).css({
            width: data[0].iWidth,
            height: data[0].iLabHeight,
            "min-height": 100,
            top: data[0].iConY,
            left: data[0].iConX,
            position: "absolute"
        });
    }
}
//对象数组分组
function jsonByGroup(arr) {
    console.log(arr);
    var map = {},
        dest = [];
    for(var i = 0; i < arr.length; i++){
        var ai = arr[i];
        if(!map[ai.c_id]){
            dest.push({
                // cTableName: ai.cTableName,
                c_id: ai.c_id,
                cFormName:ai. cFormName,
                cTableName: ai.cTableName,
                type: ai.type,
                data: [ai],
                gridColumns: ai.gridColumns,
                iConX: ai.iConX,
                iConY: ai.iConY,
                iLabHeight: ai.iLabHeight,
                iLabWidth: ai.iLabWidth,
                iWidth: ai.iWidth
            });
            map[ai.c_id] = ai;
        }else{
            for(var j = 0; j < dest.length; j++){
                var dj = dest[j];
                if(dj.c_id == ai.c_id){
                    dj.data.push(ai);
                    break;
                }
            }
        }
    }
    // console.log(dest,'分组后');
    return dest;
}
//实例化组件
function showForm(data,status) {
    console.log(data);
    cFormName = data[0].cFormName;
    $("#formName").append("<h2>"+ cFormName +"</h2>");//表标题

    for(var i = 0; i < data.length; i++){

        var type = data[i].type;

        if(type.indexOf('tab_')>-1) {
            var id = data[i].tabs_id;
            var tabs = mini.get(id);
            var tabEl = tabs.getTabBodyEl(tabs.getTab(data[i].tab_id));
            var param = {
                area: "div[id='" + tabEl.id + "']",
                c_id: id,//整个页签
                tab_id: data[i].tab_id//插入的当前页签
            }
            create(type,data[i],"div[id='" + tabEl.id + "']");
        }else {
            create(type,data[i],'#formField',status);
        }
    }
    create_table(arr_table);
    create_table(arr_tab_table,'tab');
}
//创建文本框
function create(type, data, area) {

    if (type == 'table') {// 表格
        arr_table.push(data);
        arr_cMath_child.push($.parseJSON(data.cMath).newStrEn);

    } else if (type == 'tab') {// 页签
        // create_tab(data);
        // arr_tab.push(data);
    } else if (type == 'tab_table') {// tab表格
        arr_tab_table.push(data);
        arr_cMath_child.push($.parseJSON(data.cMath).newStrEn);

    } else {
        create_base(data, area);
    }
}
//基础创建(根据状态判断是是否禁用)
function create_base(data, area) {
    console.log(data, 'data');
    var miniclass;
    if (area == '#formField') {
        miniclass = data.type;
    } else {
        miniclass = data.type.match(/tab_(\S*)/)[1];
    }
    if (miniclass.indexOf('checkbox') > -1) {
        miniclass = 'checkboxlist';
    }
    var form_items = '<div id="' + data.c_id + '" class="form_items" '
        + 'name="' + data.cTableField + '"'
        + 'style="top:' + (data.iConY) + 'px;left:' + data.iConX + 'px">'
        + '<label id="left' + data.c_id + '">' + data.cLadText
        + ':</label>\n' + '<input id="right' + data.c_id + '" name="'
        + data.cTableField + '"' + '   class="mini-' + miniclass
        + ' visibility" ';
    if (data.type.indexOf('datepicker') > -1) {
        form_items = '<div id="' + data.c_id + '" class="form_items" '
            + 'name="' + data.cTableField + '"'
            + 'style="top:' + (data.iConY) + 'px;left:' + data.iConX + 'px">'
            + '<label id="left' + data.c_id + '">' + data.cLadText
            + ':</label>\n' + '<input id="right' + data.c_id + '" name="'
            + data.cTableField + '"' + '   class="mini-' + miniclass
            + ' visibility" valueType="string"';
    } else if (data.type.indexOf('fileupload') > -1) {
        form_items = '<div id="' + data.c_id + '" class="form_items" '
            + 'name="' + data.cTableField + '"'
            + 'style="top:' + (data.iConY) + 'px;left:' + data.iConX + 'px">'
            + '<label id="left' + data.c_id + '">' + data.cLadText + ':</label>'
            + '<input id="right' + data.c_id + '" name="'
            + data.cTableField + '"' + '   class="mini-' + miniclass
            + ' visibility" valueType="string"' +
            '    flashUrl="swfupload/swfupload.swf"\n' +
            '    uploadUrl="/enclosure/uploadFile.do"\n' +
            '    onuploadsuccess="onUploadSuccess" \n' +
            '    onuploaderror="onUploadError" onfileselect="onFileSelect"\n'
        ;
    }

    // 必填
    if (data.cNull == 'true') {
        form_items += ' required="true"';
    } else {
        form_items += ' required="false"';
    }
    //因为是字符串所以这里我在转换一下子
    var sss=data.cRefObj;
    var ssa=JSON.parse(sss);
    console.log(ssa);
    //当新加的判断字段为false时，给他动态拼接onvalidation属性onGtzero(大于0)方法名
    if(ssa.cCannotbezero=="true"){

    }else if(ssa.cCannotbezero=="false"){

        form_items += 'onvalidation="onGtzero"';

    }
    // 验证
    if (data.cRequire == 'none' || data.cRequire == '' || data.cRequire == undefined) {

    } else {
        form_items += ' vtype="' + data.cRequire + '"';
    }
    if (data.type.indexOf('spinner') > -1) {
        form_items += ' decimalPlaces="'
            + data.cSpinner
            + '" allowNull="'
            + !data.cNull
            + '" value="null" allowLimitValue="false" ';
    }
    form_items += ' /></div>';
    $(area).append(form_items);
    mini.parse();
    arr_cMath_main.push({
        math: $.parseJSON(data.cMath).newStrEn
    });
    arr_cMath_main[arr_cMath_main.length - 1]['id'] = data.c_id;

    // console.log(data.type,$('#'+ data.c_id).css('marginTop'));
    $('#' + data.c_id).css({
        width: data.iWidth + 5,
        height: data.iLabHeight - 15,
        // "margin-bottom": 4
    });
    $('.form_items>span>span').css({
        height: '98%'
    });

    $('#left' + data.c_id).css({
        width: data.iWidth - data.iLabWidth,
        height: data.iLabHeight - 15,
        "text-align": "center",
        "font-size": data.cFontSize + 'px',
        "vertical-align": "middle",
        "display": "inline"
    });
    $('#right' + data.c_id).css({
        width: data.iLabWidth,
        height: data.iLabHeight - 15
    });
    if (data.cFontSize != '' || data.cFontSize != undefined) {
        $('#' + data.c_id + '>span>span>input').css('cssText',
            'font-size:' + data.cFontSize + 'px !important')
    }
    mini.parse();

    // 主表公式
    var cMath = $.parseJSON(data.cMath).newStrEn;

    // 主表 值改变时，更新其他公式结果
    mini.get('#right' + data.c_id).on("valuechanged", function (e) {
        console.log(arr_cMath_main, '所有主表公式');
        // console.log(arr_cMath_child,'所有子表公式');
        console.log(data.c_id);
        // 遍历所有主表公式
        for (var i = 0; i < arr_cMath_main.length; i++) {
            var str = arr_cMath_main[i].math;
            if (str != '' && str != undefined) {
                var param = setLinkage(e, arr_cMath_main[i].math, str, 'base');
                str = param.str;
                var mathType = param.mathType;
                var linkId = param.linkId;// 关联类型设置的id
                if (mathType == 'mathType_link') {// 关联
                    console.log(str, str);
                    if (str.fileldValue != undefined) {
                        $.ajax({
                            type: 'POST',
                            url: ajaxUrl
                                + '/formltems/casacade.do ',
                            dataType: 'json',
                            data: str,
                            success: function (data) {
                                // if(menusFormTypes ==
                                // 'complex') {
                                // for(var item in
                                // data.data[0]) {
                                // mini.get('right'+linkId).setValue(data.data[0][item]);
                                // }
                                // }else {
                                // mini.get('right'+linkId).setValue(data);
                                // }
                                if (data.data.length > 0) {
                                    for (var item in data.data[0]) {
                                        mini.get('right' + linkId).setValue(data.data[0][item]);
                                    }
                                }

                            },
                            error: function (jqXHR,
                                             textStatus,
                                             errorThrown) {

                            }
                        })
                    } else {
                        // mini.get('right'+linkId).setValue('');
                    }

                } else if (mathType == 'mathType_sumCols') {

                } else if (mathType == 'mathType_cascade') { //级联
                    console.log("进入级联计算");
                    console.log(str, "str级联计算");
                    $.ajax({
                            type: 'POST',
                            url: ajaxUrl + '/formltems/casacade.do ',
                            dataType: 'json',
                            contentType: "application/json",
                            data: JSON.stringify(str),
                            success: function (data) {
                                console.log(data);
                                if (data.state == 'success') {
                                    var casa = data.data;
                                    console.log("casa:", casa[0]);
                                    // var casaJson = casa[0];
                                    var up = {};
                                    up[e.field] = data.vale;
                                    // var value = casaJson[returnFileld];
                                    console.log("value", data.vale);
                                    var thisstr = data.data[0].returnFileld;
                                    if (thisstr.indexOf(e.sender.name) == -1) {// 不等于已填写的字段，则赋值
                                        mini.get('right' + linkId).setText(data.vale);
                                        mini.get('right' + linkId).setValue(data.vale);
                                    }
                                }
                            },
                            error: function () {

                            }
                        }
                    )
                } else if (mathType == "mathType_code") {
                    console.log("进入编号规则设置");
                    var now = new Date();
                    console.log("======str:" + JSON.stringify(str));
                    var file = str.fileld;
                    var nowYmd
                    if (file=="newDate()"){
                        var year = now.getFullYear();
                        var month = now.getMonth();
                        if (month < 10) month = "0" + ( month + 1);
                        var date = now.getDate();
                        if (date <10) date = "0" + date;
                        nowYmd = year +""+ month +""+ date +"";
                    }

                    console.log("进入编码规则设置",nowYmd);
                    console.log("linkId",linkId);
                    $.ajax({
                        url: ajaxUrl + "/sqlAction/findCode.do",
                        type : 'post',
                        data : JSON.stringify(str),
                        dataType : 'json',
                        contentType: "application/json",
                        success : function (data) {
                            console.log(data);
                            var returnObject = $.parseJSON(data.data);
                            console.log(returnObject,"returnObject");
                            var value = returnObject.valu;
                            console.log("value",value);
                            var newCode = nowYmd +""+value;
                            // if (thisstr.indexOf(e.sender.name) == -1) {// 不等于已填写的字段，则赋值
                            mini.get('right' + linkId).setText(newCode);
                            mini.get('right' + linkId).setValue(newCode);
                            // }
                        },
                        error : function () {

                        }
                    })

                } else if (mathType == "mathType_findTableSum"){
                    console.log("进入跨表求和：mathType_findTableSum")
                    console.log("子表进入跨表求和str:" + str);
                    $.ajax({
                        url : ajaxUrl + '/sqlAction/findTableSum.do',
                        type : 'post',
                        dataType: 'json',
                        contentType: "application/json",
                        data: JSON.stringify(str),
                        success : function (data) {
                            console.log("跨表求和data",data)
                            if (data.state == "success"){
                                var vale ;
                                if(data.data == ""){
                                    vale = null;
                                }else{
                                    vale = data.data;
                                }
                                mini.get('right' + linkId).setText(vale);
                                mini.get('right' + linkId).setValue(vale);
                            }else{
                                mini.alert(data.message);
                            }
                        },
                        error : function (data) {

                        }
                    })

                } else{// 计算或拼接
                    var thisStr = str.split('=')[0];// 可以赋值的字段
                    if (thisStr.indexOf(e.sender.name) == -1) {// 不等于已填写的字段，则赋值
                        mini.get('#right' + arr_cMath_main[i].id).setValue(evil(str));
                    }
                }
            }
        }

    });

    arr_main.cTableName = data.cTableName;
    arr_main.obj[data.cTableField] = "";

    // 主表 个性化
    if (data.type.indexOf('datepicker') > -1) {// 时间选择器
        if (data.cFormat != "" && data.cFormat != undefined) {
            mini.get('right' + data.c_id).setFormat(data.cFormat);
        }
    } else if (data.type.indexOf('spinner') > -1) {// 数值

    } else if (data.type.indexOf('combobox') > -1) {// 下拉框
        // console.log(data.cCombo);
        var combo_arr = data.cCombo.split(/[(\r\n)\r\n]+/);
        // console.log(combo_arr);
        var combo_data = [];
        for (var i = 0; i < combo_arr.length; i++) {
            combo_data.push({
                'id': combo_arr[i],
                'text': combo_arr[i]
            })
        }
        console.log(combo_data);
        mini.get('right' + data.c_id).setData(combo_data);

    } else if (data.type.indexOf('buttonedit') > -1) {// 参照
        mini.get('right' + data.c_id).on("buttonclick", function (e) {
            var Ref = $.parseJSON(data.ref);
            mini.open({
                url: bootPATH + "../frame/frame1/pages/formDesign/selectRef.html",
                title: "请选择",
                onload: function () { // 弹出页面加载完成
                    var iframe = this.getIFrameEl();
                    var SetData = {};
                    if (data.cTableField == "parent_level") {// 父级id
                        SetData = {
                            ref: {
                                formListId: formId
                            },
                            menusFormTypes: menusFormTypes,
                            menuId: menuId
                        };
                    } else {
                        SetData = {
                            ref: Ref.ref,
                            menuId: menuId,
                            menusFormTypes: menusFormTypes,
                        };
                        reSelectFlag = true;
                    }
                    iframe.contentWindow.SetData(SetData);
                },
                ondestroy: function (action) { // 弹出页面关闭前
                    if (action == "ok") {
                        var iframe = this.getIFrameEl();
                        var RefData = iframe.contentWindow.onTableOk();
                        RefData = mini.clone(RefData);
                        console.log(RefData, 'selectRef');
                        var refKeyArr = [];
                        var refKey = '';
                        for(var key in RefData){
                            refKeyArr.push(key);
                        }
                        refKey = refKeyArr[0];
                        refKey = refKey.split('_')[0] + '_id';
                        console.log(refKey,RefData[refKey]);

                        // console.log(Ref.ref.cTableField);
                        // console.log(RefData[Ref.ref.cTableField]);
                        if (data.cTableField == "parent_level") {// 父级id
                            mini.get('right' + data.c_id).setText(RefData[mTableName + '_name']);
                            if (RefData.mTableId == undefined) {
                                mini.get('right' + data.c_id).setValue(RefData[mTableName + '_id']);
                            } else {
                                mini.get('right' + data.c_id).setValue(RefData.mTableId);
                            }
                            mini.get('right' + data.c_id).doValueChanged();
                        } else {
                            // mini.get('right'+ data.c_id).setValue(RefData[Ref.ref.cTableField]);
                            mini.get('right' + data.c_id).setText(RefData[Ref.ref.cTableField]);
                            var newMTableName = Ref.ref.cTableName;
                            mini.get('right' + data.c_id).setValue(RefData[newMTableName + '_id']);
                            mini.get('right' + data.c_id).doValueChanged();

                        }
                        if (reSelectFlag) {// 重新选择了参照
                            // for(var p=0;p<complex_add_fields.length;p++) {
                            for (var item in complex_add_values) {
                                var name = $.parseJSON(data.ref).ref.cTableName;
                                if (item.indexOf($.parseJSON(data.ref).ref.cTableName) > -1) {
                                    complex_add_values[item] = RefData[name + '_id'];
                                }
                            }
                            // }
                            // complex_add_value = RefData.id;
                        }
                    }
                }
            })
        })
    } else {// 文本类设置长度限制
        if (data.cLength != '') {
            mini.get('right' + data.c_id).setMaxLength(data.cLength);
        }
    }
}
//表格回车时添加一行
function addRow(id) {
    var grid = mini.get(id);
    grid.on("celleditenter", function (e) {
        // console.log(grid,'回车事件');
        var index = grid.indexOf(e.record);
        if (index == grid.getData().length - 1) {
            var row = {};
            grid.addRow(row);
        }
    });
}
function create_txt(data, area) {
    console.log(data, 'data');
    if (data.cFontSize == '' || data.cFontSize == undefined) {
        data.cFontSize = 14;
    }
    var form_items = '<div id="' + data.c_id + '" class="form_items" '
        + 'style="top:' + (data.iConY) + 'px;left:' + data.iConX
        + 'px;font-size:' + data.cFontSize + 'px">' + data.cFormTitle
        + '</div>';

    $(area).append(form_items);
    $('#' + data.c_id).css({
        width: data.iWidth + 5,
        height: data.iLabHeight,
        "font-size": 14
        // "margin-bottom": 4
    });
    mini.parse();

}
//中止
function onReject(){
	console.log('中止');
    var formiddd=localStorage.getItem("formidd");
    var formId = formiddd;
    console.log(formSh);
	var mangeId = formSh.id;
    var ids = form2.getData();
	$.ajax({
		url: ajaxUrl+'/activitiTaskController/endTask.do',
		type: 'POST',
		data:{
			taskId : mangeId,
             fromId:formId
		},
		//contentType : "application/json",
		success: function(data){
			console.log(data);
			mini.alert("中止成功");
		},
		error: function(data){
			console.log(data);
			mini.alert("中止失败");
		}
	})
}

//驳回
function backUp(){
    var formiddd=localStorage.getItem("formidd");
    var formId = formiddd;
    console.log(formId);
	console.log('驳回上一步');
	var mangeId = formSh.id;
    var ids = form2.getData();
	$.ajax({
		url: ajaxUrl+'/activitiTaskController/backupgroud.do',
		type: 'POST',
		data:{
			taskId : mangeId,
            fromId:formId
		},
		//contentType : "application/json",
		success: function(data){
			console.log(data);
			alert("驳回上一步成功");
		},
		error: function(data){
			console.log(data);
			alert("驳回上一步失败");
		}
	})
}
//转发
function onForward(){
    console.log('转发');
    var mangeId = formSh.id;
    var ids = form2.getData();
//	$.ajax({
//	url: '',
//	type: 'POST',
//	contentType : "application/json",
//	success: function(data){
//		console.log(data);
//	},
//	error: function(data){
//		console.log(data);
//	}
//})
}
//查看流程图
function onSeeAcitiviImg(){
    console.log(111);
}
//委托任务(任务id/委托人id)
function onEntrustedTask(){
	
}
//关闭页面
function CloseWindow(action) {
    if (action == "close" && form.isChanged()) {
        if (confirm("数据被修改了，是否先保存？")) {
            return false;
        }
    }
    if (window.CloseOwnerWindow) return window.CloseOwnerWindow(action);
    else window.close();
}
function onOk(e) {
    SaveData();
}
function onCancel(e) {
    CloseWindow("cancel");
}
function onAddRow(e, id){
    var newRow = {
        name : "New Row"
    };
    var grid = mini.get(id);
    grid.addRow(newRow);
    // grid.beginEditCell(newRow, "LoginName");
}
function onRemoveRow(e, id) {
    var grid = mini.get(id);
    var cTableName;
    for (var k = 0; k < arr_table.length; k++) {
        if (arr_table[k].c_id == id.id) {
            cTableName = arr_table[k].cTableName;
        }
    }
    var rows = grid.getSelecteds();
    var data = grid.getData();
    if (rows.length > 0) {
        grid.removeRows(rows, true);
        console.log(rows, 'del rows');
        var del_data = [];
        for (var i = 0; i < rows.length; i++) {
            if (rows[i]._state != 'added') {
                del_data.push({
                    id : rows[i].id,
                    cTableName : cTableName
                });
            }
        }
        console.log(del_data, 'del_data');

        // $.ajax({
        // 	type : 'post',
        // 	url : ajaxUrl + '/dbsource/dbDelete.do',
        // 	data : JSON.stringify(del_data),
        // 	dataType : 'json',
        // 	contentType : 'application/json',
        // 	success : function(data) {
        // 		console.log(data);
        // 	},
        // 	error : function(message) {
        // 		// console.log(message);
        // 	}
        // })
    }
}
// jq id含有特殊字符的转义
function escapeJquery(srcString) {
    // 转义之后的结果
    var escapseResult = srcString;

    // javascript正则表达式中的特殊字符
    var jsSpecialChars = ["\\", "^", "$", "*", "?", ".", "+", "(", ")", "[",
        "]", "|", "{", "}"];

    // jquery中的特殊字符,不是正则表达式中的特殊字符
    var jquerySpecialChars = ["~", "`", "@", "#", "%", "&", "=", "'", "\"",
        ":", ";", "<", ">", ",", "/"];

    for (var i = 0; i < jsSpecialChars.length; i++) {
        escapseResult = escapseResult.replace(new RegExp("\\"
            + jsSpecialChars[i], "g"), "\\" + jsSpecialChars[i]);
    }

    for (var i = 0; i < jquerySpecialChars.length; i++) {
        escapseResult = escapseResult.replace(new RegExp(jquerySpecialChars[i],
            "g"), "\\" + jquerySpecialChars[i]);
    }

    return escapseResult;
}

//截取字符串某一位后面
//var data="aaa-bbb";
//jiequ(data,0);输出aaa；
//jiequ(data,1);输出bbb；
function jiequ(obj,state) {
    var index=obj.lastIndexOf("\_");
    if(state==0){
        obj=obj.substring(0,index);
    }else{
        obj=obj.substring(index+1,obj.length);
    }
    return obj;
}
//设置公式联动
function setLinkage(e,cMath,str,type) {
    //cMath：公式,str：可处理的公式
    var value;
    var linkType;//base类型，table类型，base+table类型
    var mathType;//联动，计算/拼接
    if(cMath.indexOf('关联')>-1) {//关联
        mathType = 'mathType_link';
        var a;var b;var c;var d;var linkId;var fileldValue;
        $.each(cMath.match(/[^\[]+(?=\])/g), function(j, word){
            if(j == 0) a = word;//须填写的字段
            if(j == 1) b = word;//关联的字段
        })
        for(var i=0;i<component_data.length;i++) {
            if(component_data[i].cTableField == a) {
                d = component_data[i].cTableName;
                linkId = component_data[i].c_id;
            }
        }
        if(type == 'table') {//子表之间关联
            fileldValue = e.row[b];
        }else if(type == 'base') {//主表之间关联
            fileldValue = e.value;
        }
        var link = {
            fileld: b,
            fileldValue: fileldValue,
            returnFileld: a,
            cTableName: d
        };
        return {str: link, linkType: linkType, mathType: mathType, linkId:linkId};

    }else {//计算/拼接
        mathType = 'mathType_other';
        $.each(cMath.match(/[^\[]+(?=\])/g), function(i, word) {//提取[]中的字段
            console.log(i, word);
            if(i>0) {//等式右侧的字段
                for(var i=0;i<component_data.length;i++) {
                    if(component_data[i].cTableField == word) {
                        if(component_data[i].type == 'table' || component_data[i].type == 'tab_table') {//变量是表格类型
                            value = e.record[word];
                            if(type == 'table' || type == 'tab_table') {
                                linkType+= 'table,';
                            }
                        }else {
                            value = mini.get('right'+component_data[i].c_id).getValue();
                            linkType+= 'base,'
                        }
                        var pattern = '\\['+word+'\\]';
                        str = str.replace(new RegExp(pattern,'g'),value);//字段替换成值
                    }
                }
            }
        });
        return {str: str, linkType: linkType, mathType: mathType, linkId:linkId};
    }
}
// 表单操作
function getForm() {
    var form = new mini.Form("#formField");
    var data = form.getData();
    console.log(data);
    return data;
}
// 编辑表单
function onEditForm() {
    // 保存按钮可用
    mini.get('saveEl').enable();
    // 单据可填写
    var formEnable = new mini.Form("formField");
    formEnable.setEnabled(true);
}
var grid_datas = [];
var arr_save = [];
var arr_tab_table = [];// 生成tab表格组件数组
// 保存
// function onSaveForm(){
//
// }

function onSaveForm() {

    // if (arr_tab_table.length > 0) {
    //     arr_table = jsonByGroup(arr_tab_table);// 表格按数据库表名分组
    // } else {
    //     arr_tab_table = mini.clone(arr_table);
    //     arr_table = jsonByGroup(arr_table);// 表格按数据库表名分组
    // }
    //
    // // arr_table = jsonByGroup(arr_tab_table);// 表格按数据库表名分组
    //
    // // 表单验证
    // var form = new mini.Form("#formField");
    // form.validate();
    // if (form.isValid() == false){
    //     return;
    // }

    // 单元格验证
    for (var p = 0; p < arr_table.length; p++) {
        var grid = mini.get(arr_table[p].c_id);
        grid.validate();
        if (grid.isValid() == false) {
            // alert("请校验输入单元格内容");
            var error = grid.getCellErrors()[0];
            grid.beginEditCell(error.record, error.column);
            return;
        }
    }

    // 提交数据
    arr_child = [];
    grid_datas = [];
    var grid_datas_id = [];
    console.log(arr_main, 'arr_main保存前');
    console.log(arr_table, 'arr_table');
    console.log(arr_tab_table, 'arr_tab_table');
    var child = [];// 合并子表数据
    child = arr_table.concat(arr_tab_table);
    var form_data = getForm();

    var pidFlag = false;
    for (item in form_data) {
        console.log(form_data[item]);
        // console.log(new Date(form_data[item]));
        // console.log(new Date(form_data[item]).toString());
        // if(new Date(form_data[item]).toString().indexOf('中国标准时间')>-1) {
        // form_data[item] = standardToDate(form_data[item],'-');
        // console.log(form_data[item]);
        // }

        for (i in arr_main.obj) {
            if (i == item) {
                arr_main.obj[i] = form_data[item];
            }
            if (i == 'parent_level') {
                pidFlag = true;
                if (arr_main.obj[i] == '') {
                    arr_main.obj[i] = -1;
                }
            }
        }
    }
    if (!pidFlag) {//没有pid
        arr_main.obj.parent_level = -1;
    }

    var time = new Date().getTime();
    // var time = guid();
    arr_main.obj.id = time;
    arr_main.tableType = 'main';
    console.log(arr_main, 'arr_main保存后');

    for (var i = 0; i < child.length; i++) {
        // 每个arr[i]是一个表格
        var id = child[i].c_id;
        var cols = child[i].gridColumns;
        var data = child[i].data;
        var grid_data = mini.get(id).getData();

        if (grid_datas_id.indexOf(id) == -1) {
            grid_datas_id.push(id);
            grid_datas.push({
                id: id,
                data: grid_data
            });

            for (var j = 0; j < grid_data.length; j++) {
                // delete grid_data[j]._id;
                // delete grid_data[j]._uid;
                delete grid_data[j]._state;
                for (var item in grid_data[j]) {
                    if (item.indexOf('$') > -1) {

                        var a = item.match(/\$(\S*)/)[1];
                        grid_data[j][a] = grid_data[j][item];
                        delete grid_data[j][item];
                    }
                }

                arr_child.push({
                    cTableName: child[i].cTableName,
                    tableType: 'child',
                    obj: grid_data[j]
                });
                arr_child[arr_child.length - 1].obj[child[i].cTableName + '_single_person_id'] = userInfoObj.userId // 制单人id
                arr_child[arr_child.length - 1].obj[child[i].cTableName + '_single_person'] = userInfoObj.uName // 制单人

                arr_child[arr_child.length - 1].obj.id = new Date().getTime() + j * 100;
                // arr_child[j].obj.id = guid();
                arr_child[arr_child.length - 1].obj.mTableId = time;

                if (arr_child[arr_child.length - 1].obj.name = 'New Row') {
                    delete arr_child[arr_child.length - 1].obj.name;
                }
            }
        }
    }

    console.log(grid_datas, 'grid_datas');
    console.log(arr_child, 'arr_child保存后');
    // console.log(grid_datas,'grid_datas');

    // 合并
    arr_save = [];
    arr_save[0] = arr_main;
    arr_save[0].grid_data = JSON.stringify(grid_datas);
    arr_save[0].cFormName = cFormName;

    // 添加默认制单人
    //arr_save[0].obj[mTableName + '_single_person_id'] = userInfoObj.userId // 制单人id
    //arr_save[0].obj[mTableName + '_single_person'] = userInfoObj.uName // 制单人
    //处理单据状态显示
    switch (arr_save[0].obj[formSh.cTableName + '_state']) {
        case '未提交':
            arr_save[0].obj[formSh.cTableName + '_state'] = '0';
            break;
        case '已提交':
            arr_save[0].obj[formSh.cTableName + '_state'] = '1';
            break;
        case '审批中':
            arr_save[0].obj[formSh.cTableName + '_state'] = '2';
            break;
        case '终审':
            arr_save[0].obj[formSh.cTableName + '_state'] = '3';
            break;
        case '驳回':
            arr_save[0].obj[formSh.cTableName + '_state'] = '4';
            break;
        case '中止':
            arr_save[0].obj[formSh.cTableName + '_state'] = '5';
            break;
        case '撤回':
            arr_save[0].obj[formSh.cTableName + '_state'] = '6';
            break;
        default:
            arr_save[0].obj[formSh.cTableName + '_state'] = '';
    }
    for (var i = 0; i < arr_child.length; i++) {

        arr_save.push(arr_child[i]);
    }
    console.log(arr_save, '保存的数据');

    var url;
    //save_backData = {id: edit_form[mTableName + '_id'].split('_')[0]};
    url = ajaxUrl + "/sqlAction/update.do";
    arr_save[i].obj.mTableId = edit_form.id;
    arr_save[i].mTableId = edit_form.id;
    //arr_save[i].formId = formId;
    arr_save[i].formId = formSh.formListId;
    // for (var i = 0; i < arr_save.length; i++) {
    //     if (i == 0) {
    //         // arr_save[i].obj.id = edit_form.id;
    //         arr_save[i].obj.id = save_backData.id;
    //         arr_save[i].formId = formId;
    //         // arr_save[i].formCode = formCode;
    //     } else {
    //         arr_save[i].obj.mTableId = edit_form.id;
    //         arr_save[i].mTableId = edit_form.id;
    //         arr_save[i].formId = formId;
    //     }
    // }

    // for (var i = 0; i < arr_save.length; i++) {
    //     for (var item in complex_add_values) {
    //         if (i == 0) {
    //             arr_save[i].obj[item] = complex_add_values[item];
    //         }
    //     }
    // }

    console.log(arr_save, '转为字符串之前');
    //arr_save.obj.derpayment_single_person = userInfoObj.userName;
    //arr_save[0].obj[mTableName + '_single_person'] = userInfoObj.userName // 制单人
    //处理单据状态显示
    switch (arr_save[0].obj[formSh.cTableName + '_state']) {
        case '已提交':
            arr_save[0].obj[formSh.cTableName + '_state'] = '1';
            break;
        case '审批中':
            arr_save[0].obj[formSh.cTableName + '_state'] = '2';
            break;
        case '终审':
            arr_save[0].obj[formSh.cTableName + '_state'] = '3';
            break;
        case '驳回':
            arr_save[0].obj[formSh.cTableName + '_state'] = '4';
            break;
        case '中止':
            arr_save[0].obj[formSh.cTableName + '_state'] = '5';
            break;
        case '撤回':
            arr_save[0].obj[formSh.cTableName + '_state'] = '6';
            break;
    }
    save_data = arr_save;// 全局

    // if(ids == 'undefined'){
    //
    // }else {
    //     console.log(arr_save[0]);
    //     console.log(typeof arr_save[0]);
    //     arr_save[0].obj['ids'] = ids;
    // }

    arr_save = JSON.stringify(arr_save);
    //console.log(complex_add_values);
    console.log(arr_save, '保存数据');
    // cTableName
    // url = "http://192.168.31.65:8080/bpm/dbsource/dbInsert.do";
    $.ajax({
        type: 'post',
        url: url,
        dataType: 'json',
        data: arr_save,
        contentType: 'application/json',
        success: function (data) {
            mini.alert(data.message);
            // var obj={id:data.id};
            // idd=mini.clone(obj);
            // idd1=idd.id;
            // localStorage.setItem("obj",JSON.stringify(obj));

            // save_backData = data;
        },
        error: function () {
            mini.alert('保存失败');
        }
    })
}